<template>
  <p style="display: inline">
    <a-upload
        name="file"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        :disabled="disabled"
        :loading="loading"
        :custom-request="customRequest"
    >
      <slot :attachment-id="modelValue">
        <a-button
            type="primary"
            :disabled="disabled"
            href="javascript:void(0)"
        >
          <upload-outlined/>
          选择文件
        </a-button>
      </slot>
    </a-upload>
    <v-attachment
        v-if="modelValue"
        :key="modelValue"
        style="margin-left: 20px;"
        :attachment-id="modelValue"
    />
  </p>
</template>
<script lang="ts" setup>
import { UploadOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import VAttachment from '@/components/VAttachment.vue'
import { uploadAttachment } from '@/api/file'

const loading = ref(false)

const props = defineProps({
  modelValue: {
    type: String,
    default: null
  },
  fileTypeCode: {//文件类型
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const beforeUpload = (file: any) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('文件不能超过10MB!')
  }
  return isLt10M
}

const customRequest = async ({ file }) => {
  console.log({ file })

  const formData = new FormData()
  formData.append('file', file as any)
   const info = await uploadAttachment(props.fileTypeCode, formData)
  emits('update:modelValue', info.id)
}

const emits = defineEmits(['update:modelValue', 'error'])
</script>
